<template>
  <div class="detail-container">
    <a-spin :spinning="loading">
      <div v-if="codeDetail" class="detail-content">
        <!-- 头部信息 -->
        <div class="detail-header card-shadow neon-border">
          <h1 class="detail-title neon-text">{{ codeDetail.title }}</h1>
          <div class="detail-meta">
            <div class="tags">
              <a-tag v-for="tag in parseTags(codeDetail.tags)" :key="tag" color="blue">
                {{ tag }}
              </a-tag>
            </div>
            <div class="info">
              <span class="view-count">👁️ {{ codeDetail.viewCount }} 次查看</span>
              <span v-if="codeDetail.creatorNickname" class="creator">👤 {{ codeDetail.creatorNickname }}</span>
              <span class="create-time">创建于 {{ formatTime(codeDetail.createTime) }}</span>
              <span v-if="codeDetail.updateTime" class="update-time">更新于 {{ formatTime(codeDetail.updateTime) }}</span>
            </div>
          </div>
        </div>

        <!-- 代码内容 -->
        <div class="detail-body card-shadow neon-border">
          <div class="action-bar">
            <a-button type="primary" @click="handleCopy">
              <template #icon>
                <CopyOutlined />
              </template>
              复制内容
            </a-button>
            <a-button @click="goBack">返回列表</a-button>
          </div>

          <div class="markdown-content">
            <MdPreview
              :modelValue="codeDetail.content"
              :theme="'dark'"
              :previewTheme="'github'"
              :codeTheme="'github'"
              :codeFoldable="false"
              :showCodeRowNumber="false"
            />
          </div>
        </div>
      </div>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getCodeById, incrementViewCount } from '@/api/code'
import type { CodeVO } from '@/types/api'
import { MdPreview } from 'md-editor-v3'
import 'md-editor-v3/lib/preview.css'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import { CopyOutlined } from '@ant-design/icons-vue'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const codeDetail = ref<CodeVO | null>(null)

// 获取代码详情
const fetchCodeDetail = async () => {
  const id = route.params.id as string
  if (!id) {
    message.error('代码ID无效')
    return
  }

  loading.value = true
  try {
    const res = await getCodeById(id)
    codeDetail.value = res.data

    // 增加浏览次数（不关心返回值）
    incrementViewCount(id).catch(() => {
      // 忽略错误，不影响用户体验
    })
  } catch (error) {
    console.error('获取代码详情失败:', error)
    message.error('获取代码详情失败')
  } finally {
    loading.value = false
  }
}

// 复制内容
const handleCopy = async () => {
  if (!codeDetail.value) return

  try {
    await navigator.clipboard.writeText(codeDetail.value.content)
    message.success('复制成功')
  } catch (error) {
    console.error('复制失败:', error)
    message.error('复制失败，请手动复制')
  }
}

// 返回列表
const goBack = () => {
  // 如果有搜索关键词，返回到带搜索参数的首页
  const keyword = route.query.keyword as string
  if (keyword) {
    router.push({ path: '/', query: { keyword } })
  } else {
    router.push('/')
  }
}

// 解析标签
const parseTags = (tags?: string) => {
  if (!tags) return []
  try {
    return JSON.parse(tags)
  } catch {
    return []
  }
}

// 格式化时间
const formatTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

onMounted(() => {
  fetchCodeDetail()
})
</script>

<style scoped>
.detail-container {
  max-width: 1200px;
  margin: 0 auto;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.detail-header {
  background: linear-gradient(135deg, #1a1f3a 0%, #0f1229 100%);
  border-radius: 12px;
  padding: 32px;
}

.detail-title {
  font-size: 32px;
  font-weight: bold;
  margin: 0 0 24px 0;
}

.detail-meta {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.info {
  display: flex;
  gap: 24px;
  font-size: 14px;
  color: #8a8fa8;
}

.view-count {
  display: flex;
  align-items: center;
  gap: 4px;
}

.detail-body {
  background: linear-gradient(135deg, #1a1f3a 0%, #0f1229 100%);
  border-radius: 12px;
  padding: 24px;
}

.action-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(74, 158, 255, 0.2);
}

.markdown-content {
  background: #0a0e27;
  border-radius: 8px;
  padding: 24px;
  min-height: 400px;
}

/* 深色主题的 Markdown 预览样式 */
:deep(.md-editor-preview) {
  background: transparent !important;
  color: #e0e0e0 !important;
}

:deep(.md-editor-preview-wrapper) {
  padding: 0 !important;
}

:deep(.md-editor-preview h1),
:deep(.md-editor-preview h2),
:deep(.md-editor-preview h3),
:deep(.md-editor-preview h4),
:deep(.md-editor-preview h5),
:deep(.md-editor-preview h6) {
  color: #4a9eff !important;
  border-bottom-color: #3d4466 !important;
}

:deep(.md-editor-preview code) {
  background: #1a1f3a !important;
  color: #4a9eff !important;
  padding: 2px 6px !important;
  border-radius: 4px !important;
}

:deep(.md-editor-preview pre) {
  background: #1a1f3a !important;
  border: 1px solid #3d4466 !important;
  border-radius: 8px !important;
  padding: 16px !important;
  overflow-x: auto !important;
}

:deep(.md-editor-preview pre code) {
  background: transparent !important;
  padding: 0 !important;
}

:deep(.md-editor-preview a) {
  color: #4a9eff !important;
}

:deep(.md-editor-preview blockquote) {
  border-left-color: #4a9eff !important;
  color: #b0b0b0 !important;
}

:deep(.md-editor-preview table) {
  border-color: #3d4466 !important;
}

:deep(.md-editor-preview th),
:deep(.md-editor-preview td) {
  border-color: #3d4466 !important;
}

:deep(.md-editor-preview th) {
  background: #1a1f3a !important;
}

:deep(.md-editor-preview tr:nth-child(2n)) {
  background: rgba(26, 31, 58, 0.3) !important;
}
</style>

